package com.codexsoft.test;

import com.codexsoft.test.entities.User;
import com.codexsoft.test.jpamodel.EMF;
import org.apache.wicket.markup.html.panel.Panel;
import javax.persistence.EntityManager;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: Admin
 * Date: 23.08.11
 * Time: 12:45
 * To change this template use File | Settings | File Templates.
 */
public class LoginPage extends Panel {
    public LoginPage(String id) {
        super(id);
        EntityManager em = EMF.get().createEntityManager();
        String query = "SELECT FROM " + User.class.getName();
        List<User> userList = em.createQuery(query).getResultList();
        User loggeduser = LastLoggedUser(userList);
        if (IsUserLogged(userList) && (loggeduser != null)){
            add(new SalutUserPanel("panel"));
        }else
            add(new AuthorizationPanel("panel"));
        em.close();
    }

    private boolean IsUserLogged(List<User> userList) {
        boolean result = false;
        for (User u : userList)
            if (u.isLogged())
                result = true;
        return result;
    }

    private User LastLoggedUser(List<User> userList) {
        User result = null;
        for (User u : userList)
            if (u.isLogged())
                result = u;
        return result;
    }
}
